<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="68px"
    >
      <el-form-item label="用户名" prop="name">
        <el-input
            v-model="queryParams.name"
            placeholder="请输入用户名"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickName">
        <el-input
            v-model="queryParams.nickName"
            placeholder="请输入用户昵称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="telePhone">
        <el-input
            v-model="queryParams.telePhone"
            placeholder="请输入手机号码"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="用户类型" prop="userType">
        <el-select
            v-model="queryParams.userType"
            placeholder="请选择用户类型"
            clearable
            class="!w-240px"
        >
          <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.PORTAL_USER_TYPE)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
            type="primary"
            plain
            @click="openForm('create')"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <!-- 补充：批量删除按钮（可选，根据需求保留） -->
        <el-button
            type="danger"
            plain
            @click="handleDeleteBatch"
            :disabled="checkedIds.length === 0"
            class="ml-4"
        >
          <Icon icon="ep:delete" class="mr-5px" /> 批量删除
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
        row-key="id"
        v-loading="loading"
        :data="list"
        :stripe="true"
        :show-overflow-tooltip="true"
        @selection-change="handleRowCheckboxChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="用户名" align="center" prop="name" />
      <el-table-column label="用户昵称" align="center" prop="nickName" />
      <el-table-column label="手机号码" align="center" prop="telePhone" />
      <el-table-column label="微信号" align="center" prop="wechat" />
      <el-table-column label="电子邮箱" align="center" prop="email" />
      <el-table-column label="用户类型" align="center" prop="userType">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.PORTAL_USER_TYPE" :value="scope.row.userType" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="180px">
        <template #default="scope">
          <el-button
              link
              type="primary"
              @click="openForm('update', scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
              link
              type="warning"
              @click="openPasswordForm(scope.row.id)"
          >
            修改密码
          </el-button>
          <el-button
              link
              type="danger"
              @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：新增/编辑用户 -->
  <UserForm ref="formRef" @success="getList" />

  <!-- 表单弹窗：单独修改密码 -->
  <PasswordForm ref="passwordFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { UserApi, User } from '@/api/portal/user'
import UserForm from './UserForm.vue'
import PasswordForm from './PasswordForm.vue' // 引入密码弹窗
import { DICT_TYPE, getIntDictOptions } from "@/utils/dict";

/** 门户网站用户 列表页 */
defineOptions({ name: 'User' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// 列表数据
const loading = ref(true)
const list = ref<User[]>([])
const total = ref(0)

// 搜索参数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  nickName: undefined,
  telePhone: undefined,
  wechat: undefined,
  email: undefined,
  password: undefined,
  userType: undefined,
  delFlag: undefined,
  createTime: [],
  modifyTime: [],
  creatorId: undefined,
  orgCode: undefined
})

// 表单Ref
const queryFormRef = ref()
const formRef = ref() // 新增/编辑表单
const passwordFormRef = ref() // 密码修改表单

// 批量操作相关
const checkedIds = ref<number[]>([])
const handleRowCheckboxChange = (records: User[]) => {
  checkedIds.value = records.map(item => item.id)
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await UserApi.getUserPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置搜索按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 打开新增/编辑表单 */
const openForm = (type: 'create' | 'update', id?: number) => {
  formRef.value.open(type, id)
}

/** 打开修改密码弹窗 */
const openPasswordForm = (userId: number) => {
  passwordFormRef.value.open(userId)
}

/** 单个删除操作 */
const handleDelete = async (id: number) => {
  try {
    // 二次确认
    await message.delConfirm()
    // 调用删除接口
    await UserApi.deleteUser(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch (error) {
    // 捕获异常，避免页面卡死
    console.error('删除失败:', error)
  }
}

/** 批量删除操作 */
const handleDeleteBatch = async () => {
  if (checkedIds.value.length === 0) {
    message.warning(t('common.pleaseSelectAtLeastOne'))
    return
  }

  try {
    await message.delConfirm()
    await UserApi.deleteUserList(checkedIds.value)
    message.success(t('common.delSuccess'))
    // 清空选中状态
    checkedIds.value = []
    // 刷新列表
    await getList()
  } catch (error) {
    console.error('批量删除失败:', error)
  }
}

/** 页面初始化加载列表 */
onMounted(() => {
  getList()
})
</script>
